package com.njtoyo.taxi.admin.library.huawei;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class PrivacyNumberHelper {
    @Value("${config.huawei.privateNumber.appKey}")
    private String appKey;

    @Value("${config.huawei.privateNumber.appSecret}")
    private String appSecret;

    @Value("${config.huawei.privateNumber.ompDomainName}")
    private String ompDomainName;

    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";

    /**
     * 获取录音文件下载地址
     * @param recordDomain 录音文件存储的服务器域名
     * @param fileName 录音文件名
     * @param count 调用次数
     * @return 录音文件下载地址
     */
    public String getRecordDownloadLink(String recordDomain, String fileName, int count) {
        String url = String.format("%s/rest/provision/voice/record/v1.0?recordDomain=%s&fileName=%s", ompDomainName, recordDomain, fileName);
        HttpsURLConnection connection = null;
        log.info("Request Url: {}", url);
        try {
            URL realUrl = new URL(url);
            connection = (HttpsURLConnection) realUrl.openConnection();
            connection.setHostnameVerifier((hostname, session) -> true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Authorization", "WSSE realm=\"SDP\", profile=\"UsernameToken\", type=\"Appkey\"");
            connection.setRequestProperty("X-WSSE", buildWsseHeader());
            connection.setInstanceFollowRedirects(false); //设置本次连接不自动处理重定向
            connection.connect();
            log.info("Get Response Message {}", connection.getContent());
            if (connection.getResponseCode() == 301) {
                return connection.getHeaderField("Location");
            }
        } catch (Exception e) {
            log.info("Send GET request catch exception: {}", e.getMessage());
            if (count < 3) { //重试三次
                return this.getRecordDownloadLink(recordDomain, fileName, count++);
            }
        }
        return null;
    }

    private String buildWsseHeader() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date());
        String nonce = UUID.randomUUID().toString().replace("-", "");

        MessageDigest md;
        byte[] passwordDigest = null;

        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update((nonce + time + appSecret).getBytes());
            passwordDigest = md.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest);
        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }
}
